package com.jeesite.modules.fl.service;

import java.util.Iterator;
import java.util.List;

import javax.validation.ConstraintViolationException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.jeesite.common.entity.Page;
import com.jeesite.common.service.CrudService;
import com.jeesite.common.service.ServiceException;
import com.jeesite.common.utils.excel.ExcelImport;
import com.jeesite.common.validator.ValidatorUtils;
import com.jeesite.modules.fl.dao.LeaguerDao;
import com.jeesite.modules.fl.entity.Leaguer;
import com.jeesite.modules.sys.entity.User;
import com.jeesite.modules.sys.service.UserService;

@Service
@Transactional(readOnly=true)
public class LeaguerService extends CrudService<LeaguerDao,Leaguer>{
	
	@Autowired
	private UserService userService;
	
	/**
	 * 获取单条数据
	 * @param leaguer
	 * @return
	 */
	@Override
	public Leaguer get(Leaguer leaguer) {
		Leaguer entity = super.get(leaguer);
		return entity;
	}
	
	public Leaguer getByCellphone(String cellphone) {
		List<Leaguer> leaguers = dao.findByCellphone(cellphone);
		if(leaguers.isEmpty()){
			return null;
		}else{
			return leaguers.get(0);
		}
	}
	
	/**
	 * 查询分页数据
	 * @param page 分页对象
	 * @param leaguer
	 * @return
	 */
	@Override
	public Page<Leaguer> findPage(Page<Leaguer> page, Leaguer leaguer) {
		return super.findPage(page, leaguer);
	}
	
	/**
	 * 保存数据（插入或更新）
	 * @param leaguer
	 */
	@Override
	@Transactional(readOnly=false)
	public void save(Leaguer leaguer) {
		super.save(leaguer);
		User user = dao.findUser(leaguer.getCellphone());
		if(user == null){
			user = new User();
			user.setPassword(leaguer.getPassword());
		}
		user.setWxOpenid(leaguer.getOpenId());
		user.setLoginCode(leaguer.getCellphone());
		user.setUserName(leaguer.getName());
		user.setUserType("leaguer");
		user.setRefCode(leaguer.getId());
		user.setRefName(leaguer.getName());
		user.setStatus("0");
		userService.save(user);
	}

	/**
	 * 更新状态
	 * @param leaguer
	 */
	@Override
	@Transactional(readOnly=false)
	public void updateStatus(Leaguer leaguer) {
		super.updateStatus(leaguer);
	}
	
	/**
	 * 删除数据
	 * @param leaguer
	 */
	@Override
	@Transactional(readOnly=false)
	public void delete(Leaguer leaguer) {
		super.delete(leaguer);
		User entity = new User();
		entity.setLoginCode(leaguer.getCellphone());
		User user = userService.getByLoginCode(entity);
		userService.delete(user);
	}
	
	@SuppressWarnings("rawtypes")
	@Transactional(readOnly=false)
	public String importData(MultipartFile file, Boolean isUpdateSupport)
    {
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        if(file == null)
            throw new ServiceException("请选择导入的数据文件！");
        ExcelImport ei = null;
        
        try
        {
        	ei = new ExcelImport(file, 2, Integer.valueOf(0));
        	List list = ei.getDataList(Leaguer.class, new String[0]);
            for(Iterator iterator = list.iterator(); iterator.hasNext();)
            {
            	Leaguer leaguer = (Leaguer)iterator.next();
                try
                {
                	Leaguer c = getByCellphone(leaguer.getCellphone());
                    if(c == null)
                    {
                        save(leaguer);
                        successNum++;
                        successMsg.append((new StringBuilder()).append("<br/>").append(successNum).append("、会员 ").append(leaguer.getName()).append(" 导入成功").toString());
                    } else if(isUpdateSupport.booleanValue())
                    {
                    	leaguer.setId(c.getId());
                        save(leaguer);
                        successNum++;
                        successMsg.append((new StringBuilder()).append("<br/>").append(successNum).append("、会员 ").append(leaguer.getName()).append(" 更新成功").toString());
                    } else
                    {
                        failureNum++;
                        failureMsg.append((new StringBuilder()).append("<br/>").append(failureNum).append("、会员 ").append(leaguer.getName()).append(" 已存在").toString());
                    }
                }
                catch(Exception e)
                {
                    failureNum++;
                    String msg = (new StringBuilder()).append("<br/>").append(failureNum).append("、会员 ").append(leaguer.getName()).append(" 导入失败：").toString();
                    if(e instanceof ConstraintViolationException)
                    {
                        List messageList = ValidatorUtils.extractPropertyAndMessageAsList((ConstraintViolationException)e, ": ");
                        for(Iterator iterator1 = messageList.iterator(); iterator1.hasNext();)
                        {
                            String message = (String)iterator1.next();
                            msg = (new StringBuilder()).append(msg).append(message).append("; ").toString();
                        }

                    } else
                    {
                        msg = (new StringBuilder()).append(msg).append(e.getMessage()).toString();
                    }
                    failureMsg.append(msg);
                    logger.error(msg, e);
                }
            }

        }
        catch(Throwable throwable2)
        {
        	throwable2.printStackTrace();
        }
        finally
        {
            if(ei != null) 
            	ei.close();
        }
        if(failureNum > 0)
        {
            failureMsg.insert(0, (new StringBuilder()).append("很抱歉，导入失败！共 ").append(failureNum).append(" 条数据格式不正确，错误如下：").toString());
            throw new ServiceException(failureMsg.toString());
        } else
        {
            successMsg.insert(0, (new StringBuilder()).append("恭喜您，数据已全部导入成功！共 ").append(successNum).append(" 条，数据如下：").toString());
            return successMsg.toString();
        }
    }

}
